package com.momo.web.controller.common;

import com.google.common.collect.Lists;
import com.momo.common.common.JSONResult;
import com.momo.common.res.upload.UploadRes;
import com.momo.common.util.snowFlake.SystemClock;
import com.momo.common.util.upload.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;

/**
 * Created by MOMO on 2019/4/26.
 */
@RestController
@RequestMapping(value = "/platform/common", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@Slf4j
public class FileController {
    private final String path = File.separator + "opt" + File.separator + "momo" + File.separator + "static" + File.separator + "images" + File.separator + "images" + File.separator + "0";

    @RequestMapping(value = "/file/upload/v1")
    public JSONResult upload(@RequestParam("files") MultipartFile[] files) throws Exception {
        if (files.length == 0) {
            return JSONResult.errorMap("无上传文件");
        }
        List<UploadRes> fileNameList = Lists.newArrayList();
        for (int i = 0; i < files.length; i++) {
            // 验证非空
            if (StringUtils.isBlank(files[0].getOriginalFilename())) {
                continue;
            }
            String fileName = SystemClock.now() + "_" + files[i].getOriginalFilename();
            if (StringUtils.isBlank(fileName)) {

                continue;
            }
            //File.separator+
            FileUtil.uploadFile(files[i].getBytes(), path, fileName);
            UploadRes uploadRes = new UploadRes();
            uploadRes.setData("文件上传成功");
            uploadRes.setFileName("/images/0/" + fileName);
            uploadRes.setUrl("http://111.231.117.239/images/");
            fileNameList.add(uploadRes);
        }

        return JSONResult.ok(fileNameList);
    }

    // 删除文件
    @PostMapping("/file/deleteFile/v1")
    public JSONResult delFile(@RequestBody UploadRes uploadRes) {

        File file = new File(path + uploadRes.getFileName());
        if (file.exists()) {
            if (file.delete()) {
                return JSONResult.ok("文件删除成功");
            } else {
                return JSONResult.errorMap("文件删除失败");
            }
        } else {
            return JSONResult.errorMap("文件不存在");
        }
    }
}
